---
import { getCollection } from "astro:content";
import BaseLayout from "../../layouts/BaseLayout.astro";
import BlogPost from "../../components/BlogPost.astro";

export async function getStaticPaths() {
  const allPosts = await getCollection("blog");

  const uniqueTags = [
    ...new Set(allPosts.map((post: any) => post.data.tags).flat()),
  ];

  return uniqueTags.map((tag) => {
    const filteredPosts = allPosts.filter((post: any) =>
      post.data.tags.includes(tag)
    );
    return {
      params: { tag },
      props: { posts: filteredPosts },
    };
  });
}

const { tag } = Astro.params;
const { posts } = Astro.props;
---

<BaseLayout pageTitle={tag}>
  <p>包含「{tag}」标签的文章</p>
  <ul>
    {
      posts.map((post) => (
        <BlogPost url={`/posts/${post.id}/`} title={post.data.title} />
      ))
    }
  </ul>
</BaseLayout>